import cn.hutool.core.convert.Convert;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import utils.CharByteKit;

import java.io.IOException;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/11 17:06
 * @Version 1.0
 */
public class ZooAcl {
    // 首先创建一个包含权限信息的客户端
    // 创建一个数据节点
    // 然后使用另外一个不包含权限信息的客户端访问
    // ACL理论：https://www.jianshu.com/p/64f525a5a347
    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        String hostPort = "127.0.0.1:2181";
        String zooDataPath = "/Auth";
        byte[] zooData = null;
        ZooKeeper zk = new ZooKeeper(hostPort, 2000, null);
        zk.addAuthInfo("digest","foo:true".getBytes());
        zk.create(zooDataPath, "init".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.EPHEMERAL);
        System.out.println("创建好了一个有权限的节点");

        System.out.println("新建客户端去访问");
        try {
            ZooKeeper zk2 = new ZooKeeper(hostPort, 2000, null);
//            zk2.addAuthInfo("digest","foo:true".getBytes());
            byte[] data = zk2.getData(zooDataPath, false, null);
            System.out.println(CharByteKit.bytesToStr(data));
        } catch (IOException e) {
            System.out.println("IO错误");
        } catch (KeeperException.NoAuthException e) {
            System.out.println("无访问权限");
        } catch (InterruptedException e) {
            System.out.println("异常中断");
        }

    }
}
